import { Controller, Get, Put, Post, Body, Request, UseGuards, Param, BadRequestException, UseInterceptors, UploadedFile, NotFoundException, InternalServerErrorException } from '@nestjs/common';
import { ApiTags, ApiOperation, ApiBearerAuth, ApiResponse, ApiConsumes, ApiBody } from '@nestjs/swagger';
import { FileInterceptor } from '@nestjs/platform-express';
import { diskStorage } from 'multer';
import { extname } from 'path';
import { JwtAuthGuard } from '../../guards/jwt-auth.guard';
import { UserService } from './user.service';
import { User } from './entities/user.entity';
import { UserProfileDto } from './dto/user-profile.dto';
import { ChangePasswordDto } from './dto/change-password.dto';
import { UpdateProfileDto } from './dto/update-profile.dto';

@ApiTags('用户')
@Controller('user')
export class UserController {
  constructor(private readonly userService: UserService) {}

  @Get('info')
  @UseGuards(JwtAuthGuard)
  @ApiBearerAuth()
  @ApiOperation({ summary: '获取当前用户信息' })
  async getUserInfo(@Request() req): Promise<Partial<User>> {
    try {
      console.log('获取用户信息 - 请求用户:', req.user);
      
      const userId = req.user.id;
      if (!userId) {
        console.error('获取用户信息 - 请求中没有用户ID');
        throw new BadRequestException('无效的用户信息');
      }
      
      console.log(`尝试获取用户ID ${userId} 的信息`);
      
      try {
        const userInfo = await this.userService.findOne(userId);
        console.log('返回的用户信息:', userInfo);
        return userInfo;
      } catch (error) {
        if (error instanceof NotFoundException) {
          // 如果用户不存在，可能是因为数据库中的用户ID与JWT中的不匹配
          // 尝试创建一个基本的用户信息
          console.warn(`用户ID ${userId} 不存在，创建基本用户信息`);
          
          const basicUserInfo = {
            id: userId,
            username: req.user.username || `user_${userId}`,
            nickname: `用户${userId}`,
            phone: req.user.phone || '',
            avatar: 'http://localhost:3000/uploads/avatars/default-avatar.png',
            status: 1,
            birthday: null, // 确保生日字段为 null
            createdAt: new Date(),
            updatedAt: new Date()
          };
          
          return basicUserInfo;
        }
        throw error;
      }
    } catch (error) {
      console.error('获取用户信息失败:', error);
      if (error instanceof NotFoundException || error instanceof BadRequestException) {
        throw error;
      }
      throw new InternalServerErrorException(`获取用户信息失败: ${error.message}`);
    }
  }

  @Put('info')
  @UseGuards(JwtAuthGuard)
  @ApiBearerAuth()
  @ApiOperation({ summary: '更新当前用户信息' })
  async updateCurrentUser(
    @Request() req,
    @Body() userData: UpdateProfileDto,
  ): Promise<Partial<User>> {
    try {
      console.log('更新用户信息 - 请求用户:', req.user);
      console.log('更新用户信息 - 请求数据:', userData);
      
      // 确保 gender 是数字类型
      if (userData.gender !== undefined) {
        userData.gender = Number(userData.gender);
      }
      
      // 如果提供了用户名，检查是否已存在
      if (userData.username) {
        const existingUser = await this.userService.findByUsername(userData.username);
        if (existingUser && existingUser.id !== req.user.id) {
          throw new BadRequestException('用户名已被使用');
        }
      }
      
      const updatedUser = await this.userService.update(req.user.id, userData);
      
      // 确保不返回密码
      if ('password' in updatedUser) {
        delete updatedUser.password;
      }
      
      console.log('更新后的用户信息:', updatedUser);
      
      return updatedUser;
    } catch (error) {
      console.error('更新用户信息失败:', error);
      throw error;
    }
  }

  @Get('profile')
  @UseGuards(JwtAuthGuard)
  @ApiBearerAuth()
  @ApiOperation({ summary: '获取用户个人资料' })
  @ApiResponse({ status: 200, description: '成功' })
  async getUserProfile(@Request() req): Promise<Partial<User>> {
    const userId = req.user.id;
    return this.userService.getUserProfile(userId);
  }

  @Put('profile')
  @UseGuards(JwtAuthGuard)
  @ApiBearerAuth()
  @ApiOperation({ summary: '更新用户个人资料' })
  @ApiResponse({ status: 200, description: '成功' })
  async updateUserProfile(
    @Request() req,
    @Body() profileDto: UserProfileDto,
  ): Promise<Partial<User>> {
    const userId = req.user.id;
    return this.userService.updateUserProfile(userId, profileDto);
  }

  @Post('change-password')
  @UseGuards(JwtAuthGuard)
  @ApiBearerAuth()
  @ApiOperation({ summary: '修改密码' })
  @ApiResponse({ status: 200, description: '成功' })
  async changePassword(
    @Request() req,
    @Body() changePasswordDto: ChangePasswordDto,
  ) {
    const userId = req.user.id;
    
    if (changePasswordDto.newPassword !== changePasswordDto.confirmPassword) {
      throw new BadRequestException('两次输入的新密码不一致');
    }
    
    await this.userService.changePassword(
      userId,
      changePasswordDto.oldPassword,
      changePasswordDto.newPassword
    );
    
    return { message: '密码修改成功' };
  }

  @Get('stats')
  @UseGuards(JwtAuthGuard)
  @ApiBearerAuth()
  @ApiOperation({ summary: '获取用户统计数据' })
  async getUserStats(@Request() req) {
    try {
      console.log('获取用户统计数据 - 请求用户:', req.user);
      
      const userId = req.user.id;
      console.log('用户ID:', userId);
      
      const stats = await this.userService.getUserStats(userId);
      console.log('获取到的统计数据:', stats);
      
      return stats;
    } catch (error) {
      console.error('获取用户统计数据失败:', error);
      throw error;
    }
  }

  @Post('avatar')
  @UseGuards(JwtAuthGuard)
  @ApiBearerAuth()
  @ApiOperation({ summary: '上传用户头像' })
  @ApiConsumes('multipart/form-data')
  @ApiBody({
    schema: {
      type: 'object',
      properties: {
        file: {
          type: 'string',
          format: 'binary',
        },
      },
    },
  })
  @UseInterceptors(
    FileInterceptor('file', {
      storage: diskStorage({
        destination: './static/uploads/avatars', // 修改为 state/upload 或相应的路径
        filename: (req, file, cb) => {
          const randomName = Array(32)
            .fill(null)
            .map(() => Math.round(Math.random() * 16).toString(16))
            .join('');
          return cb(null, `${randomName}${extname(file.originalname)}`);
        },
      }),
      fileFilter: (req, file, cb) => {
        if (!file.originalname.match(/\.(jpg|jpeg|png|gif)$/)) {
          return cb(new BadRequestException('只允许上传图片文件'), false);
        }
        cb(null, true);
      },
      limits: {
        fileSize: 1024 * 1024 * 2, // 2MB
      },
    }),
  )
  async uploadAvatar(@Request() req, @UploadedFile() file) {
    if (!file) {
      throw new BadRequestException('请选择要上传的文件');
    }

    const userId = req.user.id;
    const avatarUrl = `/static/uploads/avatars/${file.filename}`; // 修改为对应的URL路径
    
    // 更新用户头像
    await this.userService.updateUserProfile(userId, { avatar: avatarUrl });
    
    return {
      url: avatarUrl
    };
  }
}
